package com.ibp.controller;

import java.util.HashMap;
import java.util.List;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import com.ibp.response.FormResponse;
/***
 * 
 *   Controller 基类
 * 
 */
public abstract class BasicController{

	/**
	 * 处理表单验证信息
	 * @param response
	 * @param result
	 * @return
	 */
	protected <T> FormResponse<T> handleErrorResule(FormResponse<T> response ,BindingResult result){
		if(response==null){
			response = new FormResponse<T>() ;
		}
		if(result.hasErrors()){
			List<FieldError> errors = result.getFieldErrors();
			HashMap<String,String> errorMap = response.getError();
			if(errorMap == null ){
				errorMap = new HashMap<String,String>();
			}
			for(FieldError e:errors){
				String field = e.getField();
				String emessage = errorMap.get(field);
				if(emessage==null){
					errorMap.put(field, e.getDefaultMessage());
				}else{
					errorMap.put(field, emessage+","+e.getDefaultMessage());
				}
			}
			response.setError(errorMap);
		}
		
		return response ;
	}
	
	/**
	 * 处理表单验证方法
	 * @param result
	 * @return
	 */
	protected <T> FormResponse<T> handleErrorResule(BindingResult result){
		return handleErrorResule(null,result);
	}
	
}
